//################################
// 版权所有：中国农业银行软件开发中心
// 系统名称：移动办公应用-手机版
// 文件名称：myErrorLogs.js
// 创建时间：2016年09月20日
// 创建人员：Panda
// 功能说明：myErrorLogs
//################################

'use strict';

import React, {Component} from 'react';
import {
    ScrollView,
    Text,
    View,
    StyleSheet,
    TouchableOpacity,
    Image,
} from 'react-native';

import {
    Colors,
    FontSizes,
    UIConstants,
    Routes,
    PubSubTopics,
} from '../../common';

import Images from '../../images';
import MyErrorLogsItem from './myErrorLogsItem';

import LocalStorage from '../../utils/storageUtil';

import EmailEditorContainer from '../../mail/containers/emailEditorContainer';
import {toastTip} from '../../utils/toastTipUtil';

import PubSub from 'pubsub-js';

class MyErrorLogs extends Component {
    constructor(props) {
        super(props);

        this.onBackPress = this.onBackPressFunc.bind(this);
        this.onErrorLogsPress = this.onErrorLogsPressFunc.bind(this);

        this.selectedErrorLogs = [];
        this.errorLogsData = [];

        this.state = {
            errorLogs: [],
            errorLogsButtonText: UIConstants.my.selectErrorLogs,
            isSelectionMode: false,
        };
    }

    componentDidMount() {
        LocalStorage.getErrorLogs((errorLogs) => {
            errorLogs.reverse();
            this.errorLogsData = errorLogs;
            this.setState({
                errorLogs: this.errorLogsData
            });
        });

        this.onFinishedSendFeedbackEmailEvent = PubSub.subscribe(PubSubTopics.MY_FINISHED_SEND_FEEDBACK_EMAIL, () => {this.onFinishedSendFeedbackEmailHandler()});
    }

    componentWillUnmount() {
        PubSub.unsubscribe(this.onFinishedSendFeedbackEmailEvent);
    }
    
    onFinishedSendFeedbackEmailHandler() {
        this.selectedErrorLogs = [];
        this.setState({
            isSelectionMode: false,
            errorLogsButtonText: UIConstants.my.selectErrorLogs,
        });
    }
    
    onBackPressFunc() {
        if (this.state.isSelectionMode === false) {
            const {navigatorRoot} = this.props;
            navigatorRoot.pop();
        }
        else {
            this.selectedErrorLogs = [];
            this.setState({
                isSelectionMode: false,
                errorLogsButtonText: UIConstants.my.selectErrorLogs,
            });
        }
    }

    onErrorLogsPressFunc() {
        if (this.state.isSelectionMode === false) {
            //进入选择模式
            this.setState({
                isSelectionMode: true,
                errorLogsButtonText: UIConstants.my.sendErrorLogs,
            });
        }
        else if (this.state.isSelectionMode === true) {
            if (this.selectedErrorLogs.length > 0) {
                //发送反馈错误信息
                const {navigatorRoot} = this.props;
                navigatorRoot.push({
                    name: Routes.EMAIL_EDITOR,
                    component: EmailEditorContainer,
                    data: {
                        subject: UIConstants.my.customerFeedback.emailSubject,
                        body: this.getFeedbackEmailBody(),
                        to: UIConstants.my.customerFeedback.emailAddress,
                        isFeedbackEmail: true,
                    },
                    editorType: UIConstants.email.new,
                    friend: true,
                });
            }
            else {
                toastTip(UIConstants.my.errorLogsSelectionTips, 'long');
            }
        }
    }

    getFeedbackEmailBody() {
        let result = '\n\n\n\n';
        
        for (let i = 0; i < this.selectedErrorLogs.length; i++) {
            let log = this.selectedErrorLogs[i];
            result = result + JSON.stringify(log) + '\n\n';
        }

        return result;
    }

    onSelectedItem(selectedItem, isCheck) {
        if (isCheck) {
            this.selectedErrorLogs.push(selectedItem);
        }
        else {
            this.removeItemFromSelectedErrorLogs(selectedItem);
        }

        this.setState({});
    }

    removeItemFromSelectedErrorLogs(selectedItem) {
        let index = -1;
        for (let i = 0; i < this.selectedErrorLogs.length; i++) {
            let item = this.selectedErrorLogs[i];

            if (item.id === selectedItem.id) {
                index = i;
                break;
            }
        }

        if (index !== -1) {
            this.selectErrorLogs.splice(index, 1);
        }
    }

    getErrorLogsItems() {
        let errorLogsItems = [];
        for (let i = 0; i < this.errorLogsData.length; i++) {
            let json = this.errorLogsData[i];

            errorLogsItems.push(
                <MyErrorLogsItem key={json.id} item={json} isSelectionMode={this.state.isSelectionMode} onPress={(selectedItem, isChecked) => {this.onSelectedItem(selectedItem, isChecked)}} />
            );
        }
        return errorLogsItems;
    }
    
    render() {
        return (
            <View style={styles.container}>
                <View style={styles.headers}>
                    {
                        this.state.isSelectionMode === false ?
                        <TouchableOpacity style={styles.headerback} onPress={this.onBackPress}>
                            <Image source={Images.Back} style={styles.headerbackicon} resizeMode={Image.resizeMode.contain} />
                            <Text style={styles.headerbacktext}>{UIConstants.my.back}</Text>
                        </TouchableOpacity>
                        :
                        <TouchableOpacity style={styles.headerback} onPress={this.onBackPress}>
                            <Text style={styles.headerbacktext}>{UIConstants.my.cancel}</Text>
                        </TouchableOpacity>
                    }
                    
                    <Text style={styles.headertext} numberOfLines={1}>
                       {UIConstants.my.errorLogs}
                    </Text>

                    <TouchableOpacity style={[styles.headerback, {disable: (this.state.errorLogs.length > 0) ? true : false}]} onPress={this.onErrorLogsPress}>
                        <Text style={[styles.headerbacktext, {opacity: (this.state.errorLogs.length > 0) ? 1 : 0}]}>{this.state.errorLogsButtonText}</Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.listheaderview}>
                    <Text style={styles.listheadertext}>{UIConstants.my.selectTipCount.replace('{total}', this.state.errorLogs.length).replace('{counts}', this.selectedErrorLogs.length)}</Text>
                </View>
                {
                    this.state.errorLogs.length === 0 ? 
                    <Text style={styles.nodatatext}>{UIConstants.my.nodata}</Text>
                    :
                    <ScrollView>
                    {
                        this.getErrorLogsItems()
                    }
                    </ScrollView>
                }
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: 'transparent',
    },
    headers: {
        height: 60,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomWidth: 0.5,
        borderBottomColor: Colors.gray,
        backgroundColor: Colors.appHeaderBackground,
    },
    headertext: {
        flex: 1,
        fontSize: FontSizes.myItem,
        color: Colors.appHeaderText,
        textAlign: 'center',
        alignSelf: 'center',
        marginBottom: -12,
    },
    headerback: {
        flexDirection: 'row',
        marginBottom: -12,
        alignItems: 'center',
        padding: 8,
    },
    headerbackicon: {
        width: 20,
        height: 20,
    },
    headerbacktext: {
        fontSize: 17,
        color: Colors.appHeaderText,
    },
    nodatatext: {
        marginTop: 16,
        alignSelf: 'center',
        justifyContent: 'center',
        fontSize: FontSizes.myItem,
    },
    listheaderview: {
        marginTop: 8,
        flexDirection: 'row',
        backgroundColor: Colors.emailtabheader,
        paddingTop: 12,
        paddingBottom: 12,
        justifyContent: 'flex-end',
    },
    listheadertext: {
        marginRight: 10,
        fontSize: FontSizes.emailtabheadertext,
    },
});

export default MyErrorLogs;